package com.springboot.uav.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.springboot.uav.dto.AddressDto;
import com.springboot.uav.entity.Address;
import com.springboot.uav.entity.Result;
import com.springboot.uav.mapper.AddressMapper;
import com.springboot.uav.service.AddressService;
import com.springboot.uav.vo.AddressVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Objects;

@Service
@Slf4j
@RequiredArgsConstructor//注入必须初始化的值，final
public class AddressServiceIpml extends ServiceImpl<AddressMapper, Address> implements AddressService {

    private final AddressMapper addressMapper;

    //查询地址，通过userId
    @Override
    public Result getAddressByUserId(Integer userId,Integer addressType) {
        LambdaQueryWrapper<Address> Wrapper = new LambdaQueryWrapper<Address>()
                .select(Address::getAddress)
                .eq(Address::getUserId,userId)
                .eq(Address::getAddressType,addressType);
        Address address=addressMapper.selectOne(Wrapper);
        if(address==null){
            return Result.error(400,"查询失败");
        }
        return Result.success(new AddressVo(userId,address.getAddress(),addressType));
    }

    //新增地址
    @Override
    public Result addPickupAddress(AddressDto addressDto) {
        //1.查询取货地址
        LambdaQueryWrapper Wrapper = new LambdaQueryWrapper<Address>()
                .eq(Address::getAddressType,addressDto.getAddressType())
                .eq(Address::getUserId,addressDto.getUserId())
                .eq(Address::getAddress,addressDto.getAddress());
        Address pickupAddress = addressMapper.selectOne(Wrapper);

        if(Objects.nonNull(pickupAddress)){//已经有了不在添加
            return new Result(400,"添加失败：取货地址已存在",null);
        }
        //存地址
        Address savePickupAddress=new Address(null,addressDto.getUserId(),addressDto.getAddress(),addressDto.getAddressType());
        addressMapper.insert(savePickupAddress);
        return new Result(200,"取货地址添加成功",null);
    }

    @Override
    public Result addDeliveryAddress(AddressDto addressDto) {
        //1.查询取货地址
        LambdaQueryWrapper Wrapper = new LambdaQueryWrapper<Address>()
                .eq(Address::getAddressType,addressDto.getAddressType())
                .eq(Address::getUserId,addressDto.getUserId())
                .eq(Address::getAddress,addressDto.getAddress());
        Address deliveryAddress = addressMapper.selectOne(Wrapper);

        if(Objects.nonNull(deliveryAddress)){//已经有了不在添加
            return new Result(400,"添加失败：收货地址已存在",null);
        }
        //存地址
        Address saveDeliveryAddress=new Address(null,addressDto.getUserId(),addressDto.getAddress(),addressDto.getAddressType());
        addressMapper.insert(saveDeliveryAddress);
        return new Result(200,"收货地址添加成功",null);
    }
}
